package que.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import que.app.AppV1;
import que.common.Word;
import que.util.AtguiguUtil;
import que.util.FlinkSinkUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Naruto
 * @description: 将log流分流成多个流(err,action,start,page,display)
 * @Class_Name com.atguigu.realtime.app.dwd.log.Dwd_01_DwdBaseLogApp
 * @Date 2022/08/17 15:52
 */
public class DwdBaseLogBranchApp extends AppV1 {

    private final String DISPLAY = "display";
    private final String ACTION = "action";
    private final String START = "start";
    private final String PAGE = "page";
    private final String ERR = "err";
    private final String VIDEO = "video";

    public static void main(String[] args) {
        new DwdBaseLogBranchApp().init(
                9001,
                2,
        "Dwd_01_DwdBaseLogApp",
                Word.TOPIC_ODS_LOG);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        //todo 1.etl 清洗数据 ，后将数据转换成json对象
        SingleOutputStreamOperator<JSONObject> etlStream = etl(stream);

        //todo 2.使用状态纠正新老客户标识
        SingleOutputStreamOperator<JSONObject> modifiedStream = modifyCustomerSign(etlStream);

        //todo 3.使用侧输出流 将数据封装成不同的流(将每一条数据分流)
        Map<String, DataStream<JSONObject>> streams = splitStream(modifiedStream);

        //todo 4.将所有流数据发送到各自的KAFKA中
        sinkToKafka(streams);
    }



    /*
    * @author Naruto
    * @description 将所有流数据发送到kafka
    * @param streams
    * @return void
    */
    private void sinkToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_START));
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(VIDEO).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_VIDEO));
    }

    /**
    * @author Naruto
    * @description 将ods_log数据分成多种日志类型
    * @param modifiedStream
    * @return void
    */
    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> modifiedStream) {

        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>(DISPLAY) {};
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>(ACTION) {};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>(PAGE) {};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>(ERR) {};
        OutputTag<JSONObject> videoTag = new OutputTag<JSONObject>(VIDEO) {};


        SingleOutputStreamOperator<JSONObject> main = modifiedStream
                .process(new ProcessFunction<JSONObject, JSONObject>() {
                    @Override
                    public void processElement(JSONObject json,
                                               Context ctx,
                                               Collector<JSONObject> out) throws Exception {
                        // 5个流:
                        // 启动日志: 主流
                        // 页面 曝光 活动 错误  测输出流
                        if (json.containsKey(START)) {
                            out.collect(json);
                        } else {
                            JSONObject common = json.getJSONObject("common");
                            JSONObject page = json.getJSONObject(PAGE);
                            Long ts = json.getLong("ts");

                            //1.曝光
                            JSONArray displays = json.getJSONArray("displays");
//                            System.out.println(displays);
                            if (displays != null) {
                                for (int i = 0; i < displays.size(); i++) {
                                    JSONObject display = displays.getJSONObject(i);
                                    display.putAll(common);
                                    display.putAll(page);
                                    display.put("ts", ts);
                                    //放入流中
                                    ctx.output(displayTag, display);
                                }
                                json.remove("displays");
                            }

                            //2.活动
                            JSONArray actions = json.getJSONArray("actions");
                            if (actions != null) {
                                for (int i = 0; i < actions.size(); i++) {
                                    JSONObject action = actions.getJSONObject(i);
                                    action.putAll(common);
                                    action.putAll(page);
                                    action.put("ts", ts);
                                    //放入流中
                                    ctx.output(actionTag, action);
                                }
                                json.remove("actions");
                            }

                            //3.错误
                            if (json.containsKey(ERR)) {//错误信息数据 全部保留
                                ctx.output(errTag, json);
                                json.remove(ERR);
                            }

                            //4.page
                            if (page != null) {
                                ctx.output(pageTag, json);
                            }

                            //5.video
                            JSONObject video = json.getJSONObject("appVideo");
                            if (video != null) {
                                ctx.output(videoTag,json);
                            }
                        }
                    }
                });
        Map<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START,main);
        streams.put(DISPLAY,main.getSideOutput(displayTag));
        streams.put(ACTION,main.getSideOutput(actionTag));
        streams.put(PAGE,main.getSideOutput(pageTag));
        streams.put(ERR,main.getSideOutput(errTag));
        streams.put(VIDEO,main.getSideOutput(videoTag));
//        main.getSideOutput(displayTag).print("display");
//        main.getSideOutput(errTag).print("err");
//        main.getSideOutput(actionTag).print("action");
//        main.getSideOutput(pageTag).print("page");
//        main.print("main");

        return streams;
    }

    /**
    * @author Naruto
    * @description 纠正新老客户标识错误的数据
    * @param etlStream
    * @return void
    */
    private SingleOutputStreamOperator<JSONObject> modifyCustomerSign(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream
                .keyBy(json -> json.getJSONObject("common").getString("mid"))
                .map(
                    new RichMapFunction<JSONObject, JSONObject>() {

                        private ValueState<String> newDate;//新客户的登录时间

                        @Override
                        public void open(Configuration parameters) throws Exception {
                            newDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("isNewState", String.class));
                        }


                        @Override
                        public JSONObject map(JSONObject json) throws Exception {
                            JSONObject common = json.getJSONObject("common");

                            String isNew = common.getString("is_new");

                            String state = newDate.value();

                            String today = AtguiguUtil.toDate(json.getLong("ts"));

                            if("1".equals(isNew)){//当为新客户时，可能时假的新客户
                                //当isNew为1，且state为空时，为新客户，state不为空时则比较日期判断
                                if (StringUtils.isBlank(state)) {
                                    newDate.update(today);
                                }else if(!today.equals(state)){
                                    //不相等则为老客户
                                    common.put("is_new","0");
                                }
                            }else{
                                //如果是老用户，状态为空，则将日期状态更新为昨天
                                if(StringUtils.isBlank(state)){
                                    String yesterday = AtguiguUtil.toDate(json.getLong("ts") - (24 * 60 * 60 * 1000));
                                    newDate.update(yesterday);
                                }
                            }

                            return json;
                        }
                    }
                );
//                .print();
    }

    /**
    * @author Naruto
    * @description  数据清洗
    * @param stream
    * @return void
    */
    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .filter(str ->{
                    try {

                        if(StringUtils.isEmpty(str)){
                            return false;
                        }
                        JSONObject json = JSON.parseObject(str);
                        return true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("数据格式有问题："+str);
                        return false;
                    }
                })
                .map(JSON::parseObject);
    }
}
